<template>
  <el-dialog
    title="新增"
    :visible.sync="dialogVisible"
    :show="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :before-close="handleClose"
    width="500px"
    @open="open"
  >
    <el-form ref="form" v-loading="infoLoading" :model="info" :rules="rules" label-width="100px">
      <el-scrollbar ref="myScrollbar" :wrap-class="{wrapClass: true}" class="form-scrollbar">
        <div class="el-dialog-div">
          <el-form-item label="权限组" prop="RuleId">
            <el-select
              v-model="info.RuleId"
              placeholder="请选择"
              filterable
              clearable
              style="width: 100%"
              prop="module_id">
              <el-option
                v-for="item in ruleTemplates"
                v-if="item.state == 1"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名" prop="UserName">
            <el-input v-model="info.UserName" placeholder="请输入用户名,只允许英文数字"
                      @input="checkTrim('UserName')"/>
          </el-form-item>
          <el-form-item label="用户姓名" prop="TrueName">
            <el-input v-model="info.TrueName" placeholder="请输入姓名"
                      @input="checkTrim('TrueName')"/>
          </el-form-item>
          <el-form-item label="公司名称">
            <el-input v-model="info.CompanyName" placeholder="不填则默认用户姓名"/>
          </el-form-item>
          <el-form-item label="输入密码" prop="Password">
            <el-input v-model="info.Password" placeholder="请输入密码" show-password/>
          </el-form-item>
          <el-form-item label="再次输入密码" prop="CheckPassword">
            <el-input v-model="info.CheckPassword" placeholder="请再次输入密码" show-password/>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="info.Email"/>
          </el-form-item>
          <el-form-item label="账号有效期" prop="Validity">
            <el-date-picker
              style="width: 100%"
              v-model="info.Validity"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <template v-if="isOpenUser == 1">
            <el-form-item label="用户数量">
              <el-radio-group v-model="info.IsOpenUser">
                <el-radio :label="1">不限制</el-radio>
                <el-radio :label="2">限制</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="info.IsOpenUser == 2" label="可开通用户数">
              <el-input v-model="info.OpenUserNum" type="number" @blur="checkOpenUserNum()">
                <template slot="append">个</template>
              </el-input>
            </el-form-item>
            </template>
          <template v-else>
<!--            <el-form-item label="用户限制">-->
<!--              <el-input v-model="openUserNum" :disabled="true">-->
<!--                <template slot="append">个</template>-->
<!--              </el-input>-->
<!--            </el-form-item>-->
            <el-form-item label="可开通用户数">
              <el-input
                v-model="info.OpenUserNum"
                type="number"
                @blur="checkOpenUserNum"
              >
                <template slot="append">个</template>
              </el-input>
            </el-form-item>
          </template>
          <template v-if="isUnlimitedPoints === 1">
            <el-form-item label="积分使用限制">
              <el-radio-group v-model="info.IsUnlimitedPoints">
                <el-radio :label="1">不限制</el-radio>
                <el-radio :label="2">限制</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="info.IsUnlimitedPoints === 2" label="可使用积分">
              <el-input v-model="info.NumberOfPoints" type="number" @input="checkNumberOfPoints">
                <template slot="append">分</template>
              </el-input>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="公司剩余积分">
              <el-input v-model="numberOfPoints" :disabled="true">
                <template slot="append">分</template>
              </el-input>
            </el-form-item>
            <el-form-item label="可使用积分">
              <el-input
                v-model="info.NumberOfPoints"
                type="number"
                @input="checkNumberOfPoints"
              >
                <template slot="append">分</template>
              </el-input>
            </el-form-item>
          </template>

          <el-form-item label="状态">
            <el-radio-group v-model="info.State">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="isSysAdmin" label="商标" prop="OemId">
            <el-select v-model="info.OemId" placeholder="请选择商标" filterable style="width: 100%">
              <el-option
                v-for="item in oems"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-alert
              title="商标选择后无法修改，谨慎选择"
              type="warning"
              :closable="false"
              show-icon
            />
          </el-form-item>
        </div>
      </el-scrollbar>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="12" class="btnEdit">
          <el-button :disabled="infoLoading" type="primary" @click="subInfo">确 定</el-button>
        </el-col>
        <el-col :span="12" class="btnEdit">
          <el-button @click="handleClose">取 消</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<style scoped>

/deep/ .el-dialog {
  min-width: 470px;
  max-width: 500px;
}

/deep/ .el-dialog__body {
  padding: 0;
}

.form-scrollbar {
  height: 600px;
}

.el-dialog-div {
  padding: 20px 20px 0 20px;
  min-width: 400px;
}

.el-alert {
  height: 30px;
}
</style>

<script>
import { postAction } from '@/api/common'
import common from '@/utils/common'

export default {
  name: 'add',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.info.Password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      isSysAdmin: false,
      dialogVisible: this.show,
      isChange: false,
      initForm: true,
      // 页面元素
      info: {
        UserName: '',
        TrueName: '',
        CompanyName: '',
        Password: '',
        CheckPassword: '',
        Email: '',
        RuleId: '',
        Validity: '',
        State: 1,
        OemId: '',
        IsOpenUser: 2,
        OpenUserNum: 0,
        IsUnlimitedPoints: 2,
        NumberOfPoints: 0
      },
      infoLoading: true,

      isOpenUser: 1,
      isUnlimitedPoints: 1,
      openUserNum: 0,
      numberOfPoints: 0,
      limitValidity: '',
      oems: [],
      ruleTemplates: [],

      // 验证
      rules: {
        RuleId: [
          { required: true, message: '请选择权限组', trigger: 'change' }
        ],
        UserName: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          { min: 2, max: 16, message: '用户名长度在 2 到 16 个字符', trigger: 'blur' }
        ],
        TrueName: [
          { required: true, message: '请输入用户姓名', trigger: 'change' }
        ],
        Password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        CheckPassword: [
          { validator: validatePass, trigger: 'blur' }
        ],
        Validity: [
          { required: true, message: '请选择有效期', trigger: 'change' }
        ],
        OemId: [
          { required: true, message: '请选择商标', trigger: 'change' }
        ]
      },

      // pickerOptions: this.dateOptions()
    }
  },
  watch: {
    show() {
      this.dialogVisible = this.show
      this.initForm = true
    },
    info: {
      handler: function() {
        if (this.initForm) {
          this.isChange = false
          this.initForm = false
        } else {
          this.isChange = true
        }
      },
      deep: true
    }
  },

  methods: {
    async open() {
      this.infoLoading = true
      // 页面重置
      this.$nextTick(() => {
        this.$refs.myScrollbar.wrap.scrollTop = 0
        this.$refs.form.clearValidate()
      })

      const { data } = await postAction({ }, 'userCompany/GetAddLimit')

      this.isOpenUser = data.isOpenUser
      this.openUserNum = data.openUserNum
      this.isUnlimitedPoints = data.isUnlimitedPoints
      this.numberOfPoints = data.numberOfPoints
      this.limitValidity = data.limitValidity
      this.oems = data.oems
      this.info.OemId = data.oemId
      this.ruleTemplates = data.ruleTemplates
      this.isSysAdmin = data.isSysAdmin
      this.infoLoading = false
    },
    subInfo() {
      this.$refs.form.validate(async(valid) => {
        // form验证
        if (valid) {
          this.infoLoading = true
          console.log(this.info)
          await postAction(this.info, 'userCompany/SubAddInfo').then(_ => {
            this.infoLoading = false
            this.closeAction()
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })

          }).then(_ => {
            this.infoLoading = false
          })

        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    checkTrim(obj) {
      this.info[obj] = common.checkAllTrim(this.info[obj])
    },
    checkOpenUserNum() {
      const OpenUserNum = Number(this.info.OpenUserNum)
      if (this.isOpenUser == 1) {
        this.info.OpenUserNum = common.compare(OpenUserNum, 0)
      } else {
        let maxOpenUserNum = this.openUserNum
        console.log(maxOpenUserNum)
        if(this.openUserNum > 0){
          maxOpenUserNum -= 1
        }
        console.log(OpenUserNum,maxOpenUserNum)
        this.info.OpenUserNum = common.compare(OpenUserNum, 0, maxOpenUserNum)
      }
    },
    checkNumberOfPoints() {
      const NumberOfPoints = Number(this.info.NumberOfPoints)
      if (this.isUnlimitedPoints === 1) {
        this.info.NumberOfPoints = common.compare(NumberOfPoints, 0)
      } else {
        this.info.NumberOfPoints = common.compare(NumberOfPoints, 0, this.numberOfPoints)
      }
    },
    dateOptions() {
      // 13位时间戳
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const self = this
      return {
        disabledDate(time) {
          return time.getTime() > new Date(self.limitValidity).getTime() || time.getTime() < Date.now()
        }
      }
    },
    handleClose(done) {
      if (this.isChange) {
        this.$confirm('您有未保存的修改，确定关闭此页吗？', '提示', {
          type: 'warning'
        })
          .then(_ => {
            this.$emit('update:show', false)
          })
          // eslint-disable-next-line @typescript-eslint/no-empty-function
          .catch(_ => {
          })
      } else {
        this.$emit('update:show', false)
      }
    },
    closeAction() {
      this.$emit('closeAction')
    }
  }
}
</script>
